<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\AppBaseController;
use App\Models\DateCollection;
use App\Models\EnterCarFlow;
use App\Models\FlowCollection;
use App\Models\PayFee;
use App\Models\ParkRecord;
use App\Models\LiftPole;
use App\Models\ParkInfo;
use Illuminate\Http\Request;
use Cache;

class OverViewController extends AppBaseController
{

    /**
     * 流量总览
     *
     * @param Request $request
     * @return mixed
     */
    public function total(Request $request)
    {
        $this->validate($request, ['start_time' => 'required|date', 'end_time' => 'required|date']);

        $parks = $request->get('park_code', $this->getParkCodes($this->getUserParks()));

        if(in_array("7100000288", $parks)){
            foreach ($parks as $k=>$v) {
                if($v == "7100000290" || $v == "7100000291"){
                    unset($parks[$k]);
                }
            }
        }

        //出场流量汇总
        $leaveFlow = FlowCollection::whereIn('park_code', $parks)
            ->where('hour', '>=', $request->get('start_time'))
            ->where('hour', '<=', $request->get('end_time'))
            ->sum('leave_flow');

        //入场流量汇总
        $enterFlow = EnterCarFlow::whereIn('park_code', $parks)
            ->where('hour', '>=', $request->get('start_time'))
            ->where('hour', '<=', $request->get('end_time'))
            ->sum('flow');


        return $this->sendResponse(['leave_flow' => (int)$leaveFlow, 'enter_flow' => (int)$enterFlow], '请求成功');
    }

    /**
     * 一定时间段流量曲线
     *
     * @param Request $request
     */
    public function flowRange(Request $request)
    {
        $this->validate($request, ['start_time' => 'required|date', 'end_time' => 'required|date']);

        $parks = $request->get('park_code', $this->getParkCodes($this->getUserParks()));

        $start_time = \Carbon\Carbon::parse($request->get('start_time'));
        $end_time = \Carbon\Carbon::parse($request->get('end_time'));

        $date = [];

        while ($start_time->format('YmdH') <= $end_time->format('YmdH')) {
            $date[] = $start_time->format('Y-m-d H:i:s');
            $start_time->addHour(1);
        }


        //出场流量
        $leaveFlow = FlowCollection::whereIn('park_code', $parks)
            ->where('hour', '>=', $request->get('start_time'))
            ->where('hour', '<=', $request->get('end_time'))
            ->select([
                \DB::raw('IFNULL(SUM(leave_flow),0) as leave_flow'),
                'hour'
            ])
            ->groupBy('hour')
            ->get();

        //入场流量
        $enterFlow = EnterCarFlow::whereIn('park_code', $parks)
            ->where('hour', '>=', $request->get('start_time'))
            ->where('hour', '<=', $request->get('end_time'))
            ->groupBy('hour')
            ->select([
                \DB::raw('IFNULL(SUM(flow),0) as flow'),
                'hour'
            ])
            ->get();

        //构建曲线数据
        $data = [];
        $data['date'] = $date;
        $data['leave_flow'] = collect($date)->map(function ($item) use ($leaveFlow) {
            $v = $leaveFlow->where('hour', $item);

            return $v->count() ? (int)$v->first()->leave_flow : 0;
        })->toArray();

        $data['enter_flow'] = collect($date)->map(function ($item) use ($enterFlow) {
            $v = $enterFlow->where('hour', $item);

            return $v->count() ? (int)$v->first()->flow : 0;
        })->toArray();


        return $this->sendResponse($data, '请求成功');
    }

    /**
     * 获取查询字段
     *
     * @return mixed
     */
    private function queryField()
    {
        $carType = config('custom.pay_type');

        $field = collect($carType)->map(function ($item, $key) {
            $type = $key . '_count';
            return \DB::raw('IFNULL(SUM(' . $type . '),0) as ' . $type);
        });

        $field = $field->merge([
            \DB::raw('IFNULL(SUM(pay_amount),0) as pay_amount'),
            \DB::raw('IFNULL(SUM(pay_src_amount),0) as pay_src_amount')
        ]);

        return $field->toArray();
    }

    /**
     *收入总览
     *
     * @param Request $request
     * @return mixed
     */
    public function chargeTotal(Request $request)
    {
        $this->validate($request, [
                'start_time' => 'required|date',
                'end_time' => 'required|date',
                'park_code' => 'required']
        );

        $parks = $request->get('park_code');

        //出场流量汇总
        $field = $this->queryField();
        $charge = DateCollection::whereIn('park_code', $parks)
            ->where('hour', '>=', $request->get('start_time'))
            ->where('hour', '<', $request->get('end_time'))
            ->first($field)
            ->toArray();
        $data = [
            'pay_amount' => $charge['pay_amount'],
            'pay_src_amount' => $charge['pay_src_amount']
        ];

        $carType = config('custom.pay_type');


        $data['charge_number'] = collect(array_keys($carType))->sum(function ($item) use ($charge) {
            $type = $item . '_count';
            return $charge[$type];
        });

        return $this->sendResponse($data, '请求成功');
    }

    /**
     * 一定时间段收入
     *
     * @param Request $request
     */
    public function chargeRange(Request $request)
    {
        $this->validate($request, [
            'start_time' => 'required|date',
            'end_time' => 'required|date',
            'park_code' => 'required',
            'type'=>'integer'
        ]);

        $carType = config('custom.pay_type');

        $parks = $request->get('park_code');
        $start_time = \Carbon\Carbon::parse($request->get('start_time'));
        $end_time = \Carbon\Carbon::parse($request->get('end_time'));

        $date = [];

        while ($start_time->format('YmdH') <= $end_time->format('YmdH')) {
            $date[] = $start_time->format('Y-m-d H:i:s');
            $start_time->addHour(1);
        }

        //查询字段
        if($request->has('type') && in_array($request->get('type'),$carType)){
            $hasType = true;
            $queryType = array_search($request->type,$carType);
            $filed =  [
                 \DB::raw('IFNULL(SUM(' . $queryType . '_count),0) as charge_number' ),
                 \DB::raw('IFNULL(SUM(' . $queryType . '_amount),0) as  pay_amount' ),
                 'hour'
            ];

        }else{
            $hasType = false;
            $filed = array_merge($this->queryField(), ['hour']);
        }


        //出场流量
        $charge = DateCollection::whereIn('park_code', $parks)
            ->where('hour', '>=', $request->get('start_time'))
            ->where('hour', '<=', $request->get('end_time'))
            ->groupBy('hour')
            ->select($filed)
            ->get();

        //曲线数据汇制
        $data = [];
        $data['date'] = $date;
        $data['pay_amount'] = collect($date)->map(function ($item) use ($charge) {
            $v = $charge->where('hour', $item);
            return $v->count() ? (int)$v->first()->pay_amount : 0;
        })->toArray();

        //计算收入笔数
        $carType = collect(array_keys($carType));
        $data['charge_number'] = collect($date)->map(function ($item) use ($charge, $carType,$hasType) {
            $v = $charge->where('hour', $item);
            if ($v->count() < 1) {
                return 0;
            }

            $v=$v->first();

            //单个类型支付
            if($hasType){
                return (int)$v->charge_number;
            }

            //所有　支付类型
            return (int)$carType->sum(function ($value) use ($v) {
                $type = $value . '_count';
                return $v[$type];
            });
        })->toArray();


        return $this->sendResponse($data, '请求成功');
    }


    /**
     *  实时金额总计
     * @param Request $request
     * @return mixed
     */
    public function timeTotal(Request $request){
        $data = $request->all();
        $time = date("Y-m-d H:i:s");
        $carType = config('custom.pay_type');
        $park_arr = $this->getUserParks();
        $park_arr = $this->getParkCodes($park_arr);

        $start_time =  date("Y-m-d 00:00:00");
        $end_time =  date("Y-m-d H:i:s", time());
        // 费用
        $fee = PayFee::where("pay_time",">=",strtotime(date("Y-m-d 00:00:00")))
            ->where("pay_time","<=",time())
            ->whereIn("pay_type",$carType)
            ->whereIn("park_code",$park_arr)
            ->select(
                [
                    \DB::raw('IFNULL(count(1),0) as count'),
                    \DB::raw('IFNULL(SUM(pay_amount),0) as pay_amount'),
                    \DB::raw('IFNULL(SUM(pay_src_amount),0) as pay_src_amount')
                ]
            )
            ->first();

        $fee->time = $time;
        // 流量

        //出场流量汇总
        $leaveFlow = FlowCollection::whereIn('park_code', $park_arr)
            ->where('hour', '>=', $start_time)
            ->where('hour', '<=', $end_time)
            ->sum('leave_flow');

        //入场流量汇总
        $enterFlow = EnterCarFlow::whereIn('park_code', $park_arr)
            ->where('hour', '>=', $start_time)
            ->where('hour', '<=', $end_time)
            ->sum('flow');

        $fee->leaveFlow = $leaveFlow;
        $fee->enterFlow = $enterFlow;

        return $this->sendResponse($fee, '请求成功');
    }


    /**
     *  实时金额总计
     * @param Request $request
     * @return mixed
     */
    public function timeList(Request $request){
        $t1 = microtime(true);
        $input = $request->all();
        $time = date("Y-m-d H:i:s");
        $carType = config('custom.pay_type');
        $park_arr_name = $this->getUserParks();
        $park_arr = $this->getParkCodes($park_arr_name);
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $park_arr = $input['park_code'];
        }

        $start_time =  date("Y-m-d 00:00:00");
        $end_time =  date("Y-m-d H:i:s", time());

//        if($park_space = Cache::get('park_space')) {
            //车场总数
//            $park_space = ParkInfo::whereIn("park_code", $park_arr)->pluck("space_total", "park_code");
            $park_res = ParkInfo::whereIn("park_code", $park_arr)->select("space_total", 'space_empty',"park_code")->get();
//            Cache::put('park_space', $park_space, 3600);
//        }
        $park_total = [];
        $park_space = [];
        foreach ($park_res as $val) {
            $park_total[$val->park_code] = $val->space_total;
            $park_space[$val->park_code] = $val->space_empty;
        }


        // 费用
        $fee = PayFee::where("pay_time",">=",strtotime($start_time))
            ->where("pay_time","<=",time())
            ->whereIn("pay_type",$carType)
            ->whereIn("park_code",$park_arr)
            ->select(
                [
                    "park_code",
                    \DB::raw('IFNULL(count(1),0) as count'),
                    \DB::raw('IFNULL(SUM(pay_amount),0) as pay_amount'),
                    \DB::raw('IFNULL(SUM(pay_src_amount),0) as pay_src_amount')
                ]
            )
            ->groupBy("park_code")
            ->get();
        $data = [];
        foreach ($fee as $v) {
            $v->pay_amount = re2float($v->pay_amount/100);
            $v->pay_src_amount = re2float($v->pay_src_amount/100);
            $v->park_name = $park_arr_name[$v->park_code]??'';
            $v->space_total = $park_total[$v->park_code]??0;
            $data[$v->park_code] = $v;
        }

        //出场流量汇总
        $leaveFlow = FlowCollection::whereIn('park_code', $park_arr)
            ->where('hour', '>=', $start_time)
            ->where('hour', '<=', $end_time)
            ->select(
                [
                    "park_code",
                    \DB::raw('IFNULL(SUM(leave_flow),0) as leave_flow'),
                ]
            )
            ->groupBy("park_code")
            ->get();
        $inner_park_leaveFlow = FlowCollection::where('hour', '>=', $start_time)
            ->where('hour', '<=', $end_time)
            ->whereIn("park_code",[7100000290,7100000291])
            ->sum("leave_flow");
        foreach ( $leaveFlow as $v) {
            if(isset($data[$v->park_code])){
               if($v->park_code == 7100000288) {
                    $data[$v->park_code]['leave_flow'] = ($v->leave_flow-$inner_park_leaveFlow)>0?
                        ($v->leave_flow-$inner_park_leaveFlow):0;
                } else {
                    $data[$v->park_code]['leave_flow'] = $v->leave_flow;
                }
            }
        }

        //入场流量汇总
        $enterFlow = EnterCarFlow::whereIn('park_code', $park_arr)
            ->where('hour', '>=', $start_time)
            ->where('hour', '<=', $end_time)
            ->select(
                [
                    "park_code",
                    \DB::raw('IFNULL(SUM(flow),0) as flow'),
                ]
            )
            ->groupBy("park_code")
            ->get();

        $inner_park_enterFlow = EnterCarFlow::where('hour', '>=', $start_time)
            ->where('hour', '<=', $end_time)
            ->whereIn("park_code",[7100000290,7100000291])
            ->sum("flow");

        foreach ($enterFlow as $v) {
            if(isset($data[$v->park_code])){
               if($v->park_code == 7100000288) {
                    $data[$v->park_code]['flow'] = ($v->flow-$inner_park_enterFlow)>0?
                        ($v->flow-$inner_park_enterFlow):0;
                } else {
                    $data[$v->park_code]['flow'] = $v->flow;
                }
            }
        }

        // 场内车数量
//        $inner_car = ParkRecord::leaveFlow($park_arr);
//        foreach ($inner_car as $v) {
//            if(isset($data[$v['park_code']])){
//                $data[$v->park_code]['inner_park'] = $v->inner_park;
//                $data[$v->park_code]['park_per'] = intval($v->inner_park/$park_space[$v->park_code]*100)."%";
//            }
//        }
        foreach ($park_total as $k=>$v) {
            if(isset($data[$k])){
                $data[$k]['inner_park'] = $park_total[$k]-$park_space[$k];
                $data[$k]['park_per'] = intval(($park_total[$k]-$park_space[$k])/$park_total[$k]*100)."%";
            }
        }

        //免费抬干
        $freeCarCharge = LiftPole::where('out_time', '>=', strtotime($start_time))
            ->where('out_time', '<=', time())
            ->whereIn('park_code', $park_arr)
            ->select(
                [
                    "park_code",
                    \DB::raw('IFNULL(count(1),0) as lift_count'),
                ]
            )
            ->groupBy("park_code")
            ->get();
        foreach ($freeCarCharge as $v) {
            if(isset($data[$v->park_code])){
                $data[$v->park_code]['lift_count'] = $v->lift_count;
            }
        }
        $item_arr = ['leave_flow','flow','inner_park','park_per','lift_count'];
        $data = array_values($data);

        return $this->sendResponse($data, '请求成功');
    }

    public function innerCarNum(Request $request){
        $t1 = microtime(true);
        $input = $request->all();
        $time = date("Y-m-d H:i:s");
        $park_arr_name = $this->getUserParks();
        $park_arr = $this->getParkCodes($park_arr_name);
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $park_arr = $input['park_code'];
        }

        $start_time =  date("Y-m-d 00:00:00");
        $end_time =  date("Y-m-d H:i:s", time());

        $park_res = ParkInfo::whereIn("park_code", $park_arr)->select("space_total", 'space_empty',"park_code")->get();
        $park_total = [];
        $park_space = [];
        foreach ($park_res as $val) {
            $park_total[$val->park_code] = $val->space_total;
            $park_space[$val->park_code] = $val->space_empty;
        }
        $data = [];
        //场内车数量
        $inner_car = ParkRecord::leaveFlow($park_arr);

        foreach ($inner_car as $v) {
            $data[$v->park_code] = [];
            $data[$v->park_code]['inner_park'] = $v->inner_park;
            $data[$v->park_code]['park_per'] = $park_total[$v->park_code]>0?intval($v->inner_park/$park_total[$v->park_code]*100)."%":'0%';
        }
        return $this->sendResponse($data, '请求成功');
    }


    /**
     *  实时金额总计
     * @param Request $request
     * @return mixed
     */
    public function timeCount(Request $request){
        $input = $request->all();
        $park_arr_name = $this->getUserParks();
        $park_arr = $this->getParkCodes($park_arr_name);
        if(isset($input['park_code']) && !empty($input['park_code'])){
            $park_arr = $input['park_code'];
        }


        $park_space = ParkInfo::whereIn("park_code", $park_arr)->pluck("space_total", "park_code");

        $data = [];
        // 场内车数量
        $inner_car = ParkRecord::leaveFlow($park_arr);
        foreach ($inner_car as $v) {
            if(isset($data[$v['park_code']])){
                $data[$v->park_code]['inner_park'] = $v->inner_park;
                $data[$v->park_code]['park_per'] = $park_space[$v->park_code]>0?intval($v->inner_park/$park_space[$v->park_code]*100)."%":'0%';
            }
        }
        return $this->sendResponse($data, '请求成功');
    }


}
